import { View, Button, Image, ScrollView, Text } from "@tarojs/components";
import { Component, ReactNode } from "react";
import { AtList, AtListItem, AtSearchBar } from "taro-ui";
import i1 from "./images/i1.png";
import i2 from "./images/i2.png";
import i3 from './images/i3.png'
import Taro from "@tarojs/taro";
import "./index.scss";
import Req, { BASE_URL } from "../../utils/request";
import { delay, isEmpty } from "../../utils/kit";
import { getInfo } from "../../utils/auth";
export default class OperationManagement extends Component {
  state = {
    value: "",
    currentPage: 1,
    loading: false,
    hasMore: true,

    refreshing: false,

    total: 0,
    list: [],
  };
  onChange = (val: string) => {
    this.setState({
      value: val,
    });
  };
  onActionClick = () => {
    console.log("开始搜索");
    if (!isEmpty(this.state.value)) {
      this.setState(
        {
          currentPage: 1,
          hasMore: true,
          list: [],
        },
        () => {
          this.loadData();
        }
      );
    }
  };
  handleAdd = () => {
    Taro.navigateTo({
      url: "/pages/operation-form/index",
    });
  };
  goToDetail = (id: string) => {
    Taro.navigateTo({
      url: `/pages/operation-detail/index?id=${id}`,
    });
  };
  componentDidMount() {
    this.loadData();
    Taro.eventCenter.on("refreshData", this._onBackRefresh);
  }
  componentWillUnmount(): void {
    Taro.eventCenter.off("refreshData", this._onBackRefresh);
  }
  _onBackRefresh = (v) => {
    if (v.force) {
      this._refreshData();
    }
  };
  _refreshData = () => {
    this.setState(
      {
        value: "",
        currentPage: 1,
        loading: false,
        hasMore: true,
        total: 0,
        list: [],
      },
      () => {
        this.loadData();
      }
    );
  };
  loadData = () => {
    const user_info = getInfo();
    const { currentPage, list } = this.state;
    this.setState({
      loading: true,
    });
    return Req.get(
      "/project/progress/list",
      {
        userId: user_info.userId,
        // userId:101,
        pageNum: currentPage,
        pageSize: 10,
      },
      {
        loading: false,
      }
    )
      .then((r) => {
        if (r.total - list.length === 0 || r.rows.length < 10) {
          this.setState({
            hasMore: false,
          });
        }
        this.setState({
          refreshing: false,
          total: r.total,
          list: list.concat([...r.rows] as any),
          currentPage: currentPage + 1,
          loading: false,
        });
      })
      .catch((e) => {
        this.setState({
          refreshing: false,
          loading: false,
        });
      });
  };
  onScrollDetchEnd = () => {
    const { loading } = this.state;
    if (loading) return;
    if (this.state.hasMore) {
      delay(500).then(() => {
        this.loadData();
      });
    } else {
      this.setState({
        loading: false,
      });
    }
  };
  onRefresh = () => {
    console.log("下拉刷新中....");
    this.setState(
      {
        refreshing: true,
      },
      () => {
        delay(600).then(() => {
          this._refreshData();
        });
      }
    );
  };
  formatDate = (date: Date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");
    const seconds = String(date.getSeconds()).padStart(2, "0");

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  };
  render(): ReactNode {
    const _firstImg = (img: string): string => {
      if (img) {
        return BASE_URL + img.split(",")[0];
      }
      return i3;
    };
    return (
      <View className="om-container app-container">
        <View className="top-header">
          <AtSearchBar
            className="em-search-bar"
            value={this.state.value}
            onChange={this.onChange}
            onActionClick={this.onActionClick}
          />
          <Button onClick={this.handleAdd} className="text-button">
            <Image className="icon-1" src={i1} />
            新增
          </Button>
        </View>
        <ScrollView
          refresherTriggered={this.state.refreshing}
          refresherEnabled
          onRefresherRefresh={this.onRefresh}
          onScrollToLower={this.onScrollDetchEnd}
          enhanced
          showScrollbar={false}
          scrollY
          className="om-list"
        >
          <View>
            <AtList>
              {this.state.list.map((item: any, index) => (
                <AtListItem
                  className="no-arrow-space"
                  key={index}
                  onClick={() => {
                    this.goToDetail(item.id);
                  }}
                  note={
                    <View className="om-list-note">
                      <Image
                        mode="aspectFill"
                        className="om-list-note-i1"
                        src={_firstImg(item.img)}
                      />
                      <View className="om-list-note-v1">
                        <Text className="om-list-note-t1 two-line-max-text">
                          {item.projectName}
                        </Text>
                        <Text className="om-list-note-t2">项目营收：{(item.revenue ?? '-') + ' 万元'}</Text>
                        <View></View>
                        <Text className="om-list-note-t2">项目利润：{(item.profit ?? '-') + ' 万元'}</Text>                        <View>
                        </View>
                        {/* <View className="om-list-note-v2">
                          <Image className="om-list-note-i2" src={i2} />
                          <Text className="om-list-note-t2">
                            {item.location}
                          </Text>
                        </View> */}

                        <Text className="om-list-note-t3">截止日期：{item.deadline}</Text>
                      </View>
                    </View>
                  }
                />
              ))}
            </AtList>
            <View className="em-center-text">
              <Text>{this.state.hasMore ? "加载中..." : "没有更多了"}</Text>
            </View>
          </View>
        </ScrollView>
      </View>
    );
  }
}
